﻿IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'P_InsertEnterprise')
BEGIN
	DROP  Procedure  [esf_sso].P_InsertEnterprise
END
GO


CREATE Procedure [esf_sso].P_InsertEnterprise
	@pEnterpriseID					INT = NULL OUT
	
	,@pIdentificationNumber			VARCHAR (30)
	,@pIdentificationTypeCode		VARCHAR (60) = 'NIT'
	,@pIdentificationNumberDigit	VARCHAR (10) = NULL
	
	,@pCode							VARCHAR (50) = NULL
	,@pName							VARCHAR (50) = NULL
	,@pDescription					VARCHAR (1000) = NULL
	,@pIsEnabled					BIT = 1
	,@pURL							VARCHAR (500) = NULL


	,@pUserCreationAlias			VARCHAR (20) = 'root'
	,@pCreationDateTime				DATETIME = NULL
AS
	
	DECLARE @identificationTypeID INT

	SET @identificationTypeID = (SELECT ID FROM esf_sso.VIdentificationType WHERE Code = @pIdentificationTypeCode)


	IF @pCode IS NULL
	BEGIN
		SET @pCode = @pIdentificationTypeCode + '-' + @pIdentificationNumber + ISNULL ('-' + @pIdentificationNumberDigit, '')
	END


	IF @pCreationDateTime IS NULL
	BEGIN
		SET @pCreationDateTime = GETDATE ()
	END

	SET @pEnterpriseID = (SELECT EnterpriseID FROM [esf_sso].[Enterprise]
		WHERE 
			[IdentificationNumber] = @pIdentificationNumber
           AND [IdentificationTypeID] = @identificationTypeID
           AND (@pIdentificationNumberDigit IS NULL OR [IdentificationNumberDigit] = @pIdentificationNumberDigit))

	
	IF @pEnterpriseID IS NULL
	BEGIN
		
		INSERT INTO [esf_sso].[BasicReference] ([BasicReferenceTypeID],[Code],[Name],[Description],[IsEnabled],[CreationDateTime],UserCreationAlias, Extra_I)
		SELECT 6, @pCode, @pName, NULL, 1, @pCreationDateTime, @pUserCreationAlias, @pURL
	
		SET @pEnterpriseID = @@IDENTITY


		INSERT INTO [esf_sso].[Enterprise]
			   ([EnterpriseID]
			   ,[IdentificationNumber]
			   ,[IdentificationTypeID]
			   ,[IdentificationNumberDigit])
		SELECT
			@pEnterpriseID
			,@pIdentificationNumber
			,@identificationTypeID
			,@pIdentificationNumberDigit

	END
	ELSE
	BEGIN
		print 'The Enterprise already exists: ' + @pIdentificationTypeCode + '-' + @pIdentificationNumber + ISNULL ('-' + @pIdentificationNumberDigit, '')
	END

GO